package cn.wei.sdd.core.controller.wx;


import cn.wei.common.exception.Assert;
import cn.wei.common.result.R;
import cn.wei.common.result.ResponseEnum;
import cn.wei.sdd.base.util.JwtUtils;
import cn.wei.sdd.core.pojo.entity.TakeMoneyRecord;
import cn.wei.sdd.core.pojo.vo.TakeMoneyRecordByUserIdVO;
import cn.wei.sdd.core.pojo.vo.UserAccountVO;
import cn.wei.sdd.core.pojo.vo.takeMoneyVO;
import cn.wei.sdd.core.service.TakeMoneyRecordService;
import cn.wei.sdd.core.service.UserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 提现记录表 前端控制器
 * </p>
 *
 * @author Wei
 * @since 2021-11-10
 */
@Api(tags = "用户提现管理")
@RestController
@RequestMapping("/wxApi/core/takeMoneyRecord")
public class TakeMoneyRecordController {

    @Resource
    private TakeMoneyRecordService takeMoneyRecordService;

    @Resource
    private UserAccountService userAccountService;

    @ApiOperation("用户申请提现")
    @PostMapping("takeMoney")
    public R takeMoney(
           @RequestBody
            @ApiParam(value = "用户提现对象",required = true)
                   takeMoneyVO takeMoneyVO,
            HttpServletRequest request
            ){

        String userName = takeMoneyVO.getUserName();
        String zfbAccount = takeMoneyVO.getZfbAccount();
        BigDecimal totalAmount = takeMoneyVO.getTotalAmount();
        System.out.println(userName);
        System.out.println(zfbAccount);
        System.out.println(totalAmount);

        Assert.notEmpty(userName, ResponseEnum.USER_NAME_NULL_ERROR);
        Assert.notEmpty(zfbAccount, ResponseEnum.ZFB_WRONG_ERROR);

        //提现金额小于0
        Assert.isTrue(totalAmount.compareTo(new BigDecimal(0)) == 1, ResponseEnum.AMOUNT_ERROR);

        String token = request.getHeader("token");
        Long userType = Long.valueOf(JwtUtils.getUserType(token));
        Long userId = JwtUtils.getUserId(token);

        BigDecimal amount = userAccountService.getMyAccount(userId, userType).getAmount();
        //提现金额大于可用余额
        Assert.isTrue(totalAmount.compareTo(amount) == -1,ResponseEnum.AMOUNT_EXCESS_BALANCE);

        takeMoneyRecordService.takeMoney(takeMoneyVO,userId,userType);
        return R.ok().message("申请成功");

    }

    @ApiOperation("根据用户id获取提现申请记录")
    @GetMapping("getMyTakeMoneyList")
    public R getTakeMoneyList(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        List<TakeMoneyRecordByUserIdVO> list = takeMoneyRecordService.getTakeMoneyListByUserId(userId);
        return R.ok().data("list",list);
    }

}

